<?php

namespace app\controllers;

use Yii;
use app\models\Base;
use app\models\User;
use app\models\Good;
use app\models\Specs;
use app\models\Setting;
use app\models\OrderInfo;
use app\models\OrderInfoGood;
use app\models\OrderEvaluate;
use app\tools\Re;
use app\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use app\tools\JPushHelper;

class OrderController extends BaseController
{
	public $state_arr = ['待付款', '租赁中', '租赁中', '已完成', '已取消', '租赁中', '已评价'];

	public function behaviors() {
      $optional =  [];
      return ArrayHelper::merge(parent::behaviors(), [
        'authenticator' => [
          'class' => HttpBearerAuth::class,
          'optional' =>$optional
        ]
      ]);
  }

	//下单
	public function actionPlace() {
		//good_info[{"good_id":2,"num":2,"good_price":245.00},{"good_id":3,"num":3,"good_price":100.00}]
    	//$good_info = json_decode(Yii::$app->request->post('good_info', ''));
		$good_id = Yii::$app->request->post('good_id', 0);
		$specs_name = Yii::$app->request->post('specs_name', '');
		$num = Yii::$app->request->post('num', 0);
		$start_at = Yii::$app->request->post('start_at', 0);
		$end_at = Yii::$app->request->post('end_at', 0);
		$unit_price = Yii::$app->request->post('unit_price', 0);
		$total_price = Yii::$app->request->post('total_price', 0);
		$remark = Yii::$app->request->post('remark', '');
		$pay_type = Yii::$app->request->post('pay_type', 1);
		$address_name = Yii::$app->request->post('address_name', '');
		$address_phone = Yii::$app->request->post('address_phone', '');
		$address = Yii::$app->request->post('address', '');
		if (empty($good_id) || empty($unit_price) || empty($total_price) || empty($address_name) || empty($address_phone) || empty($address)) {
			return Re::data(null, '参数错误', Re::ERROR);
		}
		$good = Good::findOne($good_id);	
		if (empty($good)) {
			return Re::data(null, '商品信息读取错误', Re::ERROR);
		}
		$setting = Setting::findOne(1);
		$state = 0;
		/*if ($good->is_zl) {
			$state = 5;
		}*/
		$tran = Yii::$app->db->beginTransaction();
		try{
			$user = User::findOne(Yii::$app->user->id);
			$order = new OrderInfo();
			$order->user_name = $user->company_id ? $user->companyInfo->name : '';
			$order->user_id = Yii::$app->user->id;
			$order->order_sn = OrderInfo::generateCode() . date('YmdHis') . Yii::$app->user->id;
			$order->money = $total_price;
			$order->pay_type = $pay_type;
			$order->address_name = $address_name;
			$order->address_phone = $address_phone;
			$order->address = $address;
			$order->remark = $remark;
			$order->state = $state;
			$order->created_at = time();
			$order->save();
			$order_good = new OrderInfoGood();
			$order_good->order_id = $order->id;
			$order_good->good_id = $good_id;
			$order_good->num = $num;
			$order_good->unit_type = $good->unit_type;
			$order_good->unit_price = $unit_price;
			$order_good->specs_name = $specs_name;
			$order_good->start_at = $start_at;
			$order_good->end_at = $end_at;
      $order_good->lease_num = $this->getLeaseNum($start_at, $end_at, $good->unit_type);
      $order_good->send_type = $good->is_zl;
			$order_good->save();
			$tran->commit();
			$setting = Setting::findOne(1);
        	if ($setting->open_push_admin) {
				$user_admin_id_arr = User::find()->where(['status' => 1, 'is_admin' => 1])->select("id")->column();
	            $extra = [
		        	'push_type' => 'zldd',
		        	'push_user_type' => 3
		    	];
    			JPushHelper::pushNotifyByReg($user_admin_id_arr, '租赁订单通知', '有新的租赁订单，请至后台查看', $extra);
    		}
			return Re::data(['order_sn' => $order->order_sn, 'order_is_pay' => $setting->order_pay]);
		}catch (\Throwable $e){
				$tran->rollBack();
				throw $e;
		}
	}

	//订单支付
	public function actionPayOrder() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$order_info = OrderInfo::find()->where(['order_sn' => $order_sn])->one();
		if (empty($order_info)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
		}
		$order_info->state = 1;
		$order_info->pay_date = time();
		$order_info->save();
		return Re::data();
	}

	//发货
	public function actionSendOrder() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$send_name = Yii::$app->request->post('send_name', '');
		$send_code = Yii::$app->request->post('send_code', '');
		$order_info = OrderInfo::find()->where(['order_sn' => $order_sn])->one();
		if (empty($order_info)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
		}
		$order_info->state = 2;
		$order_info->order_send_name = $send_name;
		$order_info->order_send_code = $send_code;
		$order_info->send_at = time();
		$order_info->save();
		$extra = [
	        'push_type' => 'spfh',
	        'order_sn' => $order_sn,
	        'state' => ($order_info->state==1 || $order_info->state==2) ? 5 : $order_info->state,
			    'state_name' => $this->state_arr[$order_info->state],
	        'push_user_type' => 1
	    ];
	    JPushHelper::pushNotifyByReg((string)$order_info->user_id, '租赁商品发货通知', '您的租赁商品已发货，请至租赁详情查看', $extra);
		return Re::data();
	}

	//订单完成
	public function actionOrderSuccess() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$order_info = OrderInfo::find()->where(['order_sn' => $order_sn])->one();
		if (empty($order_info)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
		}
		$order_info->state = 3;
		$order_info->finsh_at = time();
		$order_info->save();
		$setting = Setting::findOne(1);
    	if ($setting->open_push_admin) {
			$user_admin_id_arr = User::find()->where(['status' => 1, 'is_admin' => 1])->select("id")->column();
            $extra = [
	        	'push_type' => 'zlwc',
	        	'push_user_type' => 3
	    	];
			JPushHelper::pushNotifyByReg($user_admin_id_arr, '租赁完成通知', '租赁单已完成，请至后台查看', $extra);
		}
		return Re::data();
	}

	//确认收货
	public function actionReceiveOrder() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$order_info = OrderInfo::find()->where(['order_sn' => $order_sn])->one();
		if (empty($order_info)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
		}
		if ($order_info->state != 2) {
			return Re::data(null, '订单状态信息异常，暂时无法操作', Re::ERROR);
		}
		$order_good = OrderInfoGood::find()->where(['order_id' => $order_info->id])->one();
		if ($order_good->good->is_zl) {
			$order_info->state = 5;
			$order_info->receive_at = time();
		} else {
			$order_info->state = 3;
			$order_info->finsh_at = time();
		}
		$order_info->save();
		return Re::data();
	}

	//取消订单
	public function actionCancelOrder() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$order_info = OrderInfo::find()->where(['order_sn' => $order_sn])->one();
		if (empty($order_info)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
		}
		if ($order_info->state >= 2) {
			return Re::data(null, '订单状态信息异常，暂时无法操作', Re::ERROR);
		}
		$order_info->state = 4;
		$order_info->save();
		return Re::data();
	}

	//修改订单收货信息
	public function actionChangeOrderAddress() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$address_name = Yii::$app->request->post('address_name', '');
		$address_phone = Yii::$app->request->post('address_phone', '');
		$address = Yii::$app->request->post('address', '');
		if (empty($order_sn) || empty($address_name) || empty($address_phone) || empty($address)) {
			return Re::data(null, '参数错误', Re::ERROR);
		}
		$order_info = OrderInfo::find()->where(['order_sn' => $order_sn])->one();
		if (empty($order_info)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
		}
		if ($order_info->state >= 2) {
			return Re::data(null, '订单状态信息异常，暂时无法操作', Re::ERROR);
		}
		$order_info->address_name = $address_name;
		$order_info->address_phone = $address_phone;
		$order_info->address = $address;
		$order_info->save();
		return Re::data();
	}

	//订单评价
	public function actionOrderEvaluate() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$star = Yii::$app->request->post('star', 0);
		$star_good = Yii::$app->request->post('star_good', 0);
		$star_service = Yii::$app->request->post('star_service', 0);
		$content = Yii::$app->request->post('content', '');
		$order_info = OrderInfo::find()->where(['order_sn' => $order_sn])->one();
		if (empty($order_info)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
		}
		if ($order_info->state != 3) {
			return Re::data(null, '订单状态信息异常，暂时无法操作', Re::ERROR);
		}
		$order_info_good = OrderInfoGood::find()->where(['order_id' => $order_info->id])->one();
		$order_evaluate = new OrderEvaluate();
		$order_evaluate->order_id = $order_info->id;
		$order_evaluate->good_id = $order_info_good->good_id;
		$order_evaluate->user_id = Yii::$app->user->id;
		$order_evaluate->star = $star;
		$order_evaluate->star_good = $star_good;
		$order_evaluate->star_service = $star_service;
		$order_evaluate->content = $content;
		$order_evaluate->created_at = time();
		$order_evaluate->save();
		$order_info->state = 6;
		$order_info->save();
		return Re::data();
	}

	//个人租赁订单数据
  public function actionOrderList(){
			$user_type = Yii::$app->request->post('user_type', 1);//1:普通用户 2:管理员
      $state = Yii::$app->request->post('state', -1);//0:待支付 1:待发货 2:待收货 3:已完成 4:已取消 5:租赁中
      $order_query = OrderInfo::find()->where(['status' => 1]);
			if ($user_type == 1) {
				$order_query->where(['user_id' => Yii::$app->user->id]);
			}
      if ($state > -1) {
        if ($state == 5) {
          $order_query->andWhere(['state' => [1,2,5]]);
        } else {
          $order_query->andWhere(['state' => $state]);
        }
      }
      $order_list = $order_query->orderBy("created_at desc")->all();
      $order_data = [];
      if ($order_list) {
        foreach ($order_list as $v) {
          $order_info_good = OrderInfoGood::find()->where(['order_id' => $v->id])->one();
          if (empty($order_info_good->good)) {
            continue;
          }
          $specs_data = [];
          $time_range = '';
          $specs_name = $order_info_good->specs_name;
          if ($specs_name) {
            $specs_name_arr = explode('_', $specs_name);
            foreach ($specs_name_arr as $v1) {
              $specs = Specs::find()->where(['name' => $v1])->andWhere("parent_id <> 0")->one();
              $specs_data[] = [
                'specs_type_name' => $specs->parent->name,
                'specs_name' => $v1
              ];
            }
          }		
          $good_data = [
            'good_id' => $order_info_good->good_id,
            'good_name' => $order_info_good->good->name,
            'good_cover' => $order_info_good->good->cover,
            'unit_price' => $order_info_good->unit_price,
            'num' => $order_info_good->num,
            'specs_data' => $specs_data,
            'unit_type' => $order_info_good->unit_type,
          ];
          if ($order_info_good->start_at) {
            $unit_type_name = $order_info_good->unit_type == 2 ? '天' : '个月';
            $time_range = date('Y-m-d', $order_info_good->start_at).'~'.date('Y-m-d', $order_info_good->end_at).' 共'.$order_info_good->lease_num.$unit_type_name;
          }
          $order_data[] = [
            'id' => $v->id,
            'order_sn' => $v->order_sn,
            'money' => bcadd($v->money, $v->money_yf, 2),
            'state' => ($v->state==1 || $v->state==2) ? 5 : $v->state,
            'state_name' => $this->state_arr[$v->state],
            'time_range' => $time_range,
            'good_data' => $good_data,
          ];
        }
      }
    return Re::data(['data' => $order_data]);
  }

  //订单详情
  public function actionOrderDetail(){
    $order_sn = Yii::$app->request->post('order_sn', '');
		$order_info = OrderInfo::find()->where(['order_sn' => $order_sn])->one();
		if (empty($order_info)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
		}
		$specs_data = [];
		$time_range = '';
		$order_info_good = OrderInfoGood::find()->where(['order_id' => $order_info->id])->one();
    $specs_name = $order_info_good->specs_name;
    if ($specs_name) {
      $specs_name_arr = explode('_', $specs_name);
      foreach ($specs_name_arr as $v) {
        $specs = Specs::find()->where(['name' => $v])->andWhere("parent_id <> 0")->one();
        $specs_data[] = [
          'specs_type_name' => $specs->parent->name,
          'specs_name' => $v
        ];
      }
    }
		$good_data = [
			'good_id' => $order_info_good->good_id,
			'good_name' => $order_info_good->good->name,
			'good_cover' => $order_info_good->good->cover,
			'unit_price' => $order_info_good->unit_price,
			'num' => $order_info_good->num,
			'specs_data' => $specs_data,
			'unit_type' => $order_info_good->unit_type,
			'lease_num' => $order_info_good->lease_num,
    ];
    $time_range = '';
		if ($order_info_good->start_at) {
      $unit_type_name = $order_info_good->unit_type == 2 ? '天' : '个月';
			$time_range = date('Y-m-d', $order_info_good->start_at).'~'.date('Y-m-d', $order_info_good->end_at).' 共'.$order_info_good->lease_num.$unit_type_name;
		}
		$orderEvaluate = OrderEvaluate::find()->where(['order_id' => $order_info->id])->one();
    $order_data = [
			'id' => $order_info->id,
			'order_sn' => $order_info->order_sn,
			'user_name' => $order_info->user_name,
			'agreement_name' => $order_info->agreement_name,
			'money_yf' => $order_info->money_yf,
			'code' => $order_info->code,
			'file' => $order_info->file,
			'money' => bcadd($order_info->money, $order_info->money_yf, 2),
			'state' => ($order_info->state==1 || $order_info->state==2) ? 5 : $order_info->state,
      'state_name' => $this->state_arr[$order_info->state],
      'good_zl' => $order_info_good->send_type,
      'send_type' => $order_info_good->send_type,
			'address_name' => $order_info->address_name,
  		'address_phone' => $order_info->address_phone,
  		'address' => $order_info->address,
			'time_range' => $time_range,
			'good_data' => $good_data,
      'remark' => $order_info->remark,
			'order_send_name' => $order_info->order_send_name,
			'order_send_code' => $order_info->order_send_code,
      'created_time' => date("Y-m-d H:i:s", $order_info->created_at),
			'pay_time' => $order_info->pay_date ? date("Y-m-d H:i:s", $order_info->pay_date) : '',
			'send_time' => $order_info->send_at ? date("Y-m-d H:i:s", $order_info->send_at) : '',
			'receive_time' => $order_info->receive_at ? date("Y-m-d H:i:s", $order_info->receive_at) : '',
			'finsh_time' => $order_info->finsh_at ? date("Y-m-d H:i:s", $order_info->finsh_at) : '',
			'cancel_time' => $order_info->cancel_at ? date("Y-m-d H:i:s", $order_info->cancel_at) : '',
			'evaluate_time' => $orderEvaluate ? date("Y-m-d H:i:s", $orderEvaluate->created_at) : '',
    ];
    return Re::data(['data' => $order_data]);
  }

	//评价详情
	public function actionOrderEvaluateDetail() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$order_info = OrderInfo::find()->where(['order_sn' => $order_sn])->one();
		if (empty($order_info)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
		}
		$orderEvaluate = OrderEvaluate::find()->where(['order_id' => $order_info->id])->one();
		if (!$orderEvaluate) {
			return Re::data(null, '暂无订单评价信息', Re::ERROR);
		}
		$data = [
			'user_name' => $orderEvaluate->user->name,
			'star' => $orderEvaluate->star,
			'star_good' => $orderEvaluate->star_good,
			'star_service' => $orderEvaluate->star_service,
			'content' => $orderEvaluate->content,
			'evaluate_time' => date("Y-m-d H:i:s", $orderEvaluate->created_at),
		];
		return Re::data(['data' => $data]);
	}

	//根据租赁时间获取时长
	public function actionGetLeasenum() {
		$start_at = Yii::$app->request->post('start_at', 0);
		$end_at = Yii::$app->request->post('end_at', 0);
		$unit_type = Yii::$app->request->post('unit_type', 2);
		$unit_price = Yii::$app->request->post('unit_price', 0);
		if (empty($start_at) || empty($end_at) || empty($unit_type) || empty($unit_price)) {
			return Re::data(null, '参数错误', Re::ERROR);
		}
		if ($unit_type == 2) {
			$lease_num = ceil(($end_at-$start_at)/3600/24);
		} else {
			list($date_start['y'], $date_start['m'], $date_start['d']) = explode("-", date('Y-m-d', $start_at));
			list($date_end['y'], $date_end['m'], $date_end['d']) = explode("-", date('Y-m-d', $end_at));
			$lease_num = abs($date_end['y'] - $date_start['y'])*12 + $date_end['m'] - $date_start['m'];
			if ((int)$date_end['d'] > (int)$date_start['d']) {
				$lease_num+= 1;
			}
		}
		$data = [
			'lease_num' => $lease_num,
			'total_price' => bcmul($lease_num, $unit_price, 2),
		];
		return Re::data(['data' => $data]);
	}

	private function getLeaseNum($start_at, $end_at, $unit_type) {
		if ($unit_type == 2) {
			$lease_num = ceil(($end_at-$start_at)/3600/24);
		} else {
			list($date_start['y'], $date_start['m'], $date_start['d']) = explode("-", date('Y-m-d', $start_at));
			list($date_end['y'], $date_end['m'], $date_end['d']) = explode("-", date('Y-m-d', $end_at));
			$lease_num = abs($date_end['y'] - $date_start['y'])*12 + $date_end['m'] - $date_start['m'];
			if ((int)$date_end['d'] > (int)$date_start['d']) {
				$lease_num+= 1;
			}
		}
		return $lease_num;
	}
}
